package com.example.smsbox;

import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.example.adapter.SmsAdapter;
import com.example.callback.onSmsReceiverListenner;
import com.example.controler.SmsReceiver;
import com.example.controler.SmsSender;
import com.example.item.ItemSMS;

public class ChatActivity extends Activity implements onSmsReceiverListenner {

	private ListView lstSMS;
	private EditText edtContent;
	private Button btnSend;
	private SmsAdapter adapter;
	private SmsReceiver smsReceiver;
	private final String number = "15555215556";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		lstSMS = (ListView) findViewById(R.id.lstSMS);
		edtContent = (EditText) findViewById(R.id.edtContent);
		btnSend = (Button) findViewById(R.id.btnSend);
		adapter = new SmsAdapter(getApplicationContext(), 1,
				new ArrayList<ItemSMS>());
		lstSMS.setAdapter(adapter);
		btnSend.setOnClickListener(btnSendClick);

		smsReceiver = new SmsReceiver(this);

		this.setTitle(number);
	}

	@Override
	protected void onResume() {
		super.onResume();
		IntentFilter filter = new IntentFilter(
				"android.provider.Telephony.SMS_RECEIVED");
		this.registerReceiver(smsReceiver, filter);
	}

	private OnClickListener btnSendClick = new OnClickListener() {

		public void onClick(View v) {
			if ("".equals(edtContent.getText().toString())) {
			} else {
				String content = edtContent.getText().toString();
				ItemSMS item = new ItemSMS();
				item.setMessaging(content);
				item.setThoigian("10h30");

				item.setGuinhan(0);
				adapter.add(item);
				adapter.notifyDataSetChanged();
				lstSMS.setSelection(adapter.getCount());

				PendingIntent pi = PendingIntent.getActivity(
						getApplicationContext(), 0, new Intent(), 0);

				SmsSender sender = SmsSender.getInstance();
				sender.sendSMS(number, content, pi);

			}
		}
	};

	public void onSmsReceiver(String address, String message) {
		ItemSMS item = new ItemSMS();
		item.setMessaging(message);

		item.setThoigian("10h30");
		item.setGuinhan(1);
		adapter.add(item);
		adapter.notifyDataSetChanged();
		lstSMS.setSelection(adapter.getCount());
	}
}
